package com.cjj.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cjj.common.convention.errorcode.BaseErrorCode;
import com.cjj.common.convention.exception.ClientException;
import com.cjj.dao.entity.TeacherInfo;
import com.cjj.dao.entity.User;
import com.cjj.dao.mapper.TeacherInfoMapper;
import com.cjj.dto.req.GetTeacherInfoListReqDTO;
import com.cjj.dto.req.ReviewTeacherInfoReqDTO;
import com.cjj.dto.req.TeacherInfoReqDTO;
import com.cjj.service.TeacherInfoService;
import com.cjj.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
public class TeacherInfoServiceImpl  extends ServiceImpl<TeacherInfoMapper, TeacherInfo> implements TeacherInfoService {

    private final UserService userService;
    /**
     * 教师信息上传
     * @param teacherInfoReqDTO 教师信息
     */
    @Override
    public void uploadTeacherInfo(TeacherInfoReqDTO teacherInfoReqDTO) {
        // 1. 参数校验
        if (teacherInfoReqDTO == null) {
            throw new ClientException("教师信息为空");
        }
        if (StringUtils.isBlank(teacherInfoReqDTO.getTeacherNumber())) {
            throw new ClientException("教师工号不能为空");
        }

        // 2. 查询数据库，是否存在该教师编号的教师信息
        LambdaQueryWrapper<TeacherInfo> queryWrapper = Wrappers.lambdaQuery(TeacherInfo.class)
                .eq(TeacherInfo::getTeacherNumber, teacherInfoReqDTO.getTeacherNumber());
        TeacherInfo existingTeacher = baseMapper.selectOne(queryWrapper);
        if (existingTeacher != null) {
            throw new ClientException("教师信息已存在");
        }

        // 3. 数据转换和保存
        TeacherInfo teacherInfo = new TeacherInfo();
        BeanUtil.copyProperties(teacherInfoReqDTO, teacherInfo); // 这里应该是从DTO复制到Entity
        teacherInfo.setIsAvailable(0); // 新添加的教师应该设置为可用，或者根据业务需求设置

        baseMapper.insert(teacherInfo);
    }

    @Override
    public IPage<TeacherInfo> getNotAvailable(Integer pageNum, Integer pageSize) {
        // 校验分页参数
        pageNum = (pageNum == null || pageNum < 1) ? 1 : pageNum;
        pageSize = (pageSize == null || pageSize < 1) ? 10 : pageSize;
        pageSize = Math.min(pageSize, 100); // 限制最大页大小


        // 创建分页对象
        Page<TeacherInfo> page = new Page<>(pageNum, pageSize);

        // 构建查询条件
        LambdaQueryWrapper<TeacherInfo> wrapper = Wrappers.lambdaQuery(TeacherInfo.class)
                .eq(TeacherInfo::getIsAvailable, 0);

        // 直接转换并返回 IPage
        return baseMapper.selectPage(page, wrapper);

    }

    /**
     * 分页查询教师信息
     * @param pageNum 页数
     * @param pageSize 页面大小
     * @param getTeacherInfoListReqDTO 包含教师名字，性别，院系
     * @return
     */
    @Override
    public IPage<TeacherInfo> getTeacherInfoList(Integer pageNum, Integer pageSize, GetTeacherInfoListReqDTO getTeacherInfoListReqDTO) {
        // 校验分页参数
        pageNum = (pageNum == null || pageNum < 1) ? 1 : pageNum;
        pageSize = (pageSize == null || pageSize < 1) ? 10 : pageSize;
        pageSize = Math.min(pageSize, 100); // 限制最大页大小


        // 创建分页对象
        Page<TeacherInfo> page = new Page<>(pageNum, pageSize);

        // 构建查询条件
        LambdaQueryWrapper<TeacherInfo> wrapper = Wrappers.lambdaQuery(TeacherInfo.class)
                .eq(StrUtil.isNotBlank(getTeacherInfoListReqDTO.getGender()),TeacherInfo::getGender,getTeacherInfoListReqDTO.getGender())
                .eq(StrUtil.isNotBlank(getTeacherInfoListReqDTO.getDepartment()),TeacherInfo::getDepartment,getTeacherInfoListReqDTO.getDepartment())
                .eq(TeacherInfo::getIsAvailable, 0)
                .like(StrUtil.isNotBlank(getTeacherInfoListReqDTO.getName()),TeacherInfo::getName,getTeacherInfoListReqDTO.getName());

        // 直接转换并返回 IPage
        return baseMapper.selectPage(page, wrapper);
    }

    /**
     * 批量审核教师信息，设置为可用状态
     * @param reviewTeacherInfoReqDTO
     */
    @Override
    public void reviewTeacherInfo(ReviewTeacherInfoReqDTO reviewTeacherInfoReqDTO) {
        if (reviewTeacherInfoReqDTO == null){
            throw new ClientException(BaseErrorCode.CLIENT_ERROR);
        }
        if (reviewTeacherInfoReqDTO.getUserId() == null){
            throw new ClientException(BaseErrorCode.CLIENT_ERROR);
        }
        if (reviewTeacherInfoReqDTO.getTeacherNumbers() == null
                || reviewTeacherInfoReqDTO.getTeacherNumbers().isEmpty()) {
            throw new ClientException("教师工号列表不能为空");
        }
        User user = userService.getById(reviewTeacherInfoReqDTO.getUserId());
        if (user == null || user.getUserType() != 2){
            throw new ClientException("当前用户非管理员");
        }
        LambdaQueryWrapper<TeacherInfo> lambdaQueryWrapper = Wrappers.lambdaQuery(TeacherInfo.class)
                .in(reviewTeacherInfoReqDTO.getTeacherNumbers() != null
                                && reviewTeacherInfoReqDTO.getTeacherNumbers().size() != 0,
                        TeacherInfo::getTeacherNumber, reviewTeacherInfoReqDTO.getTeacherNumbers())
                .eq(TeacherInfo::getIsAvailable, 0);//不可用的教师信息

        List<TeacherInfo> teacherInfos = baseMapper.selectList(lambdaQueryWrapper);
        if (teacherInfos.isEmpty()) {
            throw new ClientException("未找到需要审核的教师信息");
        }
        // 批量更新
        for (TeacherInfo teacher : teacherInfos) {
            // 只更新状态字段，保留其他所有字段不变
            LambdaUpdateWrapper<TeacherInfo> updateWrapper = Wrappers.lambdaUpdate(TeacherInfo.class)
                    .eq(TeacherInfo::getTeacherNumber, teacher.getTeacherNumber())
                    .set(TeacherInfo::getIsAvailable, 1);


            baseMapper.update(null, updateWrapper);
        }
    }
}
